package moonhy.c2dm_client;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import moonhy.c2dm_client.dw.AccountData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.taptwo.android.widget.TitleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.LinearLayout.LayoutParams;

public class AccountActivity extends Activity implements View.OnTouchListener{
	ViewFlipper flipper;
	ProgressDialog initDialog;
	
	float xAtDown;
	float xAtUp;
	
	int FIRST_CHECK = 9;
	
	int viewIdxFirst = 1;
	int viewIdxLast = -1;
	
	DateFormat dfTitle = new SimpleDateFormat("MM.yyyy");
	Date today = new Date();
	Calendar calCurrent = Calendar.getInstance();
	
	private int GROUP_CREATED_DATE;
	private int GROUP_BALANCE;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		

		super.onCreate(savedInstanceState);
        setContentView(R.layout.account_result);
        
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Editor edit = prefs.edit();
		edit.putInt("currentTab", 2);
		edit.commit();
		Log.d("C2DM", "" + prefs.getAll().toString());
        
        
        flipper = (ViewFlipper)findViewById(R.id.viewFlipper);
        flipper.setOnTouchListener(this);
        
        initDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
        
        //new initGroupInfo(this).execute();
        new getGroupBalance(this).execute();
        
        
        

        /*
        calCurrent.setTime(today);
    	initDate(1);
    	String tmpDate = dfTitle.format(calCurrent.getTime());
    	String tmpYear = tmpDate.substring(3);
    	String tmpMonth = tmpDate.substring(0,2);
    	new initPage(this, tmpYear, tmpMonth, 0).execute();
    	*/
    	
        /*
        TextView tv = new TextView(this);
        tv.setText("View 4\nDynamically added");
        tv.setTextColor(Color.CYAN);
        flipper.addView(tv);
		*/
		//new initPage(this).execute();
	}
	
	private void initDate(int denom){
		
		if(denom < 0)
			calCurrent.add( Calendar.MONTH, -1 );
		else if(denom > 0)
			calCurrent.add( Calendar.MONTH, 1 );
	}
	
	private void initThisMonthBackground(){
		calCurrent.setTime(today);
    	String tmpDate = dfTitle.format(calCurrent.getTime());
    	String tmpYear = tmpDate.substring(3);
    	String tmpMonth = tmpDate.substring(0,2);
    	new initPage(this, tmpYear, tmpMonth, FIRST_CHECK).execute();
    	
    	flipper.bringChildToFront(flipper.getChildAt(0));
	}
	
	private void initPrevMonthBackground(){
		initDate(-1);
    	String tmpDate = dfTitle.format(calCurrent.getTime());
    	String tmpYear = tmpDate.substring(3);
    	String tmpMonth = tmpDate.substring(0,2);
    	new initPage(this, tmpYear, tmpMonth, 0).execute();
	}
	
	public boolean onUp(View v, MotionEvent event) {
		return onTouch(v, event);
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		float pressDownPoint = 0;
		int flipperViewCount = flipper.getChildCount();
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		// will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH
		int screenDensity = dm.densityDpi;
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		
		

		/*
		switch (event.getAction())
	    {
	        case MotionEvent.ACTION_DOWN:
	        {
	            //Gets the startpoint for you finger
	            pressDownPoint = event.getX();
	            
	            
	            //Gets how many view there is in the viewflipper
	            flipperViewCount = flipper.getChildCount();

	            //Checks if there is a view to the left of the current view
	            //if there is, it positions it to the left of the current view
	            if (flipper.getDisplayedChild() > 0)
	            {
	                View leftChild = flipper.getChildAt(flipper.getDisplayedChild() - 1);
	                //You must set the left view to invisible or visible 
	                //or it will not move to the position you tell it
	                leftChild.setVisibility(View.INVISIBLE);
	                leftChild.layout(-screenWidth, 
	                        leftChild.getTop(), 0, 
	                        leftChild.getBottom());
	            }

	            //Same as above but for the view to the right
	            if (flipper.getDisplayedChild() < flipperViewCount - 1)
	            {
	                View rightChild = flipper.getChildAt(flipper.getDisplayedChild() + 1);
	                rightChild.setVisibility(View.INVISIBLE);
	                rightChild.layout(screenWidth, rightChild.getTop(), screenWidth * 2, 
	                        rightChild.getBottom());
	            }
	            break;
	        }
	        case MotionEvent.ACTION_UP:
	        {
	            //Gets the absolute position on the screen
	            float releasePoint = event.getRawX();

	            //Calculates if the fling is to the right or left
	//The screenDensity variable is simply the density of the device
	//Have in mind that this will not flipp the viewflipper if you drag
	//your finger less than about 0.5cm (depeding on the device)
	//In that case you need to make an animation that takes the view back
	//to its original position. Else it will just get stuck where you
	//let go with your finger.
	            //if (Math.abs(pressDownPoint - releasePoint) / screenDensity > 30){
	                if (pressDownPoint > releasePoint){
	                	flipper.setInAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_left_in));
	    		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_left_out));
	                    flipper.showNext();
	                }else{
	                	flipper.setInAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_right_in));
	    		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_right_out));
	                    flipper.showPrevious();
	                }
	            //}
	            break;
	        }
	        case MotionEvent.ACTION_MOVE:
	        {
	            View currentView = flipper.getCurrentView();

	            //Moves the current view
				//screenWidth is based on the current devices screen width
	            currentView.layout((int)(event.getRawX() - pressDownPoint), 
	                    currentView.getTop(), (int)(event.getRawX() - pressDownPoint) + screenWidth, 
	                    currentView.getBottom());

	            //Moves the view to the left if there is one
	            if (flipper.getDisplayedChild() > 0)
	            {
	                View leftChild = flipper.getChildAt(flipper.getDisplayedChild() - 1);
	                leftChild.layout((int)(event.getRawX() - pressDownPoint - screenWidth), 
	                        leftChild.getTop(), (int)(event.getRawX() - pressDownPoint), 
	                        leftChild.getBottom());

	                //Sets the left view to visible so it shows
	                if (leftChild.getVisibility() == View.INVISIBLE)
	                {
	                    leftChild.setVisibility(View.VISIBLE);
	                }
	            }

	            //Same as above but for the view to the right
	            if (flipper.getDisplayedChild() < flipperViewCount - 1)
	            {
	                View rightChild = flipper.getChildAt(flipper.getDisplayedChild() + 1);
	                rightChild.layout((int)(event.getRawX() - pressDownPoint + screenWidth), 
	                        rightChild.getTop(), (int)(event.getRawX() - pressDownPoint + (screenWidth * 2)), 
	                        rightChild.getBottom());

	                if (rightChild.getVisibility() == View.INVISIBLE)
	                {
	                    rightChild.setVisibility(View.VISIBLE);
	                }
	            }
	        }

	    }
		*/
		//Log.d("C2DM", "ACTION : " + event.getAction() + " view: " + v);
		
		flipper = (ViewFlipper)findViewById(R.id.viewFlipper);
		
		//if(v != flipper || v != (GridView)findViewById(R.id.grid)) return false;
		/*
		View currentView = flipper.getCurrentView();
		if(currentView.getParent() != null){
			currentView.getParent().requestDisallowInterceptTouchEvent(true);
		}
		*/
		
		
		if(event.getAction() == MotionEvent.ACTION_DOWN) {
			//Log.d("C2DM", " DOWN ------------------");
			xAtDown = event.getX();
		}else if(event.getAction() == MotionEvent.ACTION_MOVE){

			/*
			View currentView = flipper.getCurrentView();

            //Moves the current view
			//screenWidth is based on the current devices screen width
            currentView.layout(
            		(int)(event.getRawX() - xAtDown), 
                    currentView.getTop(), 
                    (int)(event.getRawX() - xAtDown) + screenWidth, 
                    currentView.getBottom()
            );

            //Moves the view to the left if there is one
            
            Log.d("C2DM", event.getRawX() + ">=" + xAtDown);
            if (event.getRawX() >= xAtDown){
                View leftChild = flipper.getChildAt(flipper.getDisplayedChild() + 1);
                
                leftChild.layout(
                		(currentView.getLeft() - screenWidth - 20),
                        leftChild.getTop(), 
                        (currentView.getLeft() - 20), 
                        leftChild.getBottom()
                );
                
                Log.d("C2DM", "leftChild " + (event.getRawX() - xAtDown) + "left: " + leftChild.getRight());
                
                leftChild.setVisibility(View.VISIBLE);
                //Sets the left view to visible so it shows
//                if (leftChild.getVisibility() == View.GONE)
//                {
//                    leftChild.setVisibility(View.VISIBLE);
//                }
            } else {
            	View rightChild = flipper.getChildAt(flipper.getDisplayedChild() - 1);
                rightChild.layout(
                		(currentView.getRight() + 20), 
                        rightChild.getTop(), 
                        (currentView.getRight() + screenWidth + 20), 
                        rightChild.getBottom());
                rightChild.setVisibility(View.VISIBLE);
            }
			*/
			
		}else if(event.getAction() == MotionEvent.ACTION_UP){
			xAtUp = event.getX();
			
			//Log.d("C2DM", " UP ------------------");
			if(Math.abs(xAtDown - xAtUp) / screenWidth > 0.2){
						
				if( xAtUp < xAtDown ) {
					flipper.setInAnimation(AnimationUtils.loadAnimation(this,
			        		R.anim.push_left_in));
			        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
			        		R.anim.push_left_out));
			        
			        if(flipper.getDisplayedChild() > 0){
			        	flipper.showPrevious();
			        	initDate(1);
			        }
				}
				else if (xAtUp > xAtDown){
					flipper.setInAnimation(AnimationUtils.loadAnimation(this,
			        		R.anim.push_right_in));
			        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
			        		R.anim.push_right_out));
			        
			        
			        DateFormat ymFormat = new SimpleDateFormat("yyyyMM");
			        int ymCurrent = (Integer.parseInt(ymFormat.format(calCurrent.getTime())));
			        
			        if(GROUP_CREATED_DATE <= ymCurrent){
				        flipper.showNext();
				        initDate(-1);
				        
						if( flipper.getChildAt(flipper.getDisplayedChild() + 1) == null){
					    	String tmpDate = dfTitle.format(calCurrent.getTime());
					    	String tmpYear = tmpDate.substring(3);
					    	String tmpMonth = tmpDate.substring(0,2);
					    	
					    	ymCurrent = (Integer.parseInt(ymFormat.format(calCurrent.getTime())));
					    	if(ymCurrent >= GROUP_CREATED_DATE)
					    		new initPage(this, tmpYear, tmpMonth, 0).execute();
						}
			        }else{
			        	Toast.makeText(this, "첫 데이터 입니다.", Toast.LENGTH_SHORT).show(); 
					}
				}
			}
		}
			
		return true;
	}


	
	private View createCustomView(ArrayList<memDues> memDuesList) {
        LinearLayout linearLayoutView = new LinearLayout(this);
        ListView listview = new ListView(this);
        listview.setSelector(android.R.drawable.list_selector_background);
        listview.setCacheColorHint(0x00000000);
        //ArrayAdapter<String> aa = new ArrayAdapter<memDues> (this, android.R.layout.simple_list_item_1, memDuesList);
        
        PersonAdapter aa = new PersonAdapter(this, R.layout.account_member_due_popup, memDuesList);
        listview.setAdapter(aa);
        /*
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String strNumber;
                if(position == 0) {
                    strNumber = "1번 아이템 Clicked";
                }
                else {
                    strNumber = "2번 아이템 Clicked";
                }          
                Toast.makeText(MyAlertDialog.this, strNumber, Toast.LENGTH_SHORT).show();
            }          
        });
         */
        
        TextView tv = new TextView(this);
        tv.setText(" 총 " + memDuesList.size() + "명 입금");
        linearLayoutView.setOrientation(LinearLayout.VERTICAL);
        linearLayoutView.addView(tv);
        linearLayoutView.addView(listview);
        return linearLayoutView;
    }
	
	
	private ArrayList<AccountData> setData(Context context, String frm_year, String frm_month, ArrayList<memDues> memDuesList){
		//String readNotice = readJSON("http://moonhy.mireene.com/kline/notice/notice_list.php");
		ArrayList<AccountData> md_array = new ArrayList<AccountData>();
		
		int totInAmount = 0;
		int totOutAmount = 0;
		int memberInAmount = 0;
		
		try {
			httpConnectionManager hcm = new httpConnectionManager(context);
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("frm_year", frm_year);
		    map.put("frm_month", frm_month);
		    
		    NumberFormat currencyFormatter = NumberFormat.getInstance();

			JSONObject json = new JSONObject(hcm.readJSON(getString(R.string.SERVER_URL) + "info/service_account.php", map));
			
//			Log.d("C2DM", "" + json.getJSONArray("data_result_member"));
//			Log.d("C2DM", "" + json.getJSONArray("data_result"));
			
			JSONArray json_result  = new JSONArray();
			JSONArray json_result_member = new JSONArray();
			
			if(!json.isNull("data_result")){
				json_result = json.getJSONArray("data_result");
			}
			
			if(!json.isNull("data_result_member")){
				json_result_member = json.getJSONArray("data_result_member");
			}

			
			for (int i = 0; i < json_result_member.length(); i++) {
				JSONObject jsonObject	 = json_result_member.getJSONObject(i);
				memberInAmount			+= jsonObject.getInt("KA_AMOUNT");
				
				if(jsonObject.getInt("KA_UNPAID") == 0){
					memDues setMemDuesData = new memDues(jsonObject.getString("KA_MEM_NAME"), jsonObject.getInt("KA_AMOUNT"));
					memDuesList.add(setMemDuesData);
				}
			}
			
			AccountData tmp_memAmount = new AccountData();
			tmp_memAmount.setAccTitle(frm_year + "년 " + frm_month + "월 회비");
			tmp_memAmount.setAccIn( currencyFormatter.format(memberInAmount));
			tmp_memAmount.setAccOut("0");
			md_array.add(tmp_memAmount);
			
			for(int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				AccountData tmp_nd = new AccountData();
				tmp_nd.setAccTitle(jsonObject.getString("KMA_TITLE"));
				tmp_nd.setAccIn(currencyFormatter.format(jsonObject.getInt("KMA_IN")));
				tmp_nd.setAccOut(currencyFormatter.format(jsonObject.getInt("KMA_OUT")));
				md_array.add(tmp_nd);
				
				totInAmount += jsonObject.getInt("KMA_IN");
				totOutAmount += jsonObject.getInt("KMA_OUT");
			}
			
			totInAmount += memberInAmount;
			
			AccountData tmp_totAmount = new AccountData();
			tmp_totAmount = new AccountData();
			tmp_totAmount.setAccTitle("이달의 합계");
			tmp_totAmount.setAccIn( currencyFormatter.format(totInAmount));
			tmp_totAmount.setAccOut(currencyFormatter.format(totOutAmount));
			md_array.add(tmp_totAmount);
			
		} catch (Exception e) {
			Log.e("C2DM", "====== " + e);
		}
		
		return md_array;
	}
	
			
	private class initPage extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener, OnTouchListener{
		ArrayList<AccountData> md_array;
		//private ProgressDialog dialog;
		private Context context;
		private String frm_year;
		private String frm_month;
		private int order;
		private ProgressBar dialog;
		private LinearLayout ll;
		private TextView tv;
		
		ArrayList<memDues> memDuesList = new ArrayList<memDues>();
		
		private initPage(Context context, String frm_year, String frm_month, int order){
			this.context = context;
			this.frm_year = frm_year;
			this.frm_month = frm_month;
			this.order = order;
			
			LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
        	ll = new LinearLayout(context);
        	ll.setGravity(Gravity.CENTER);
        	
        	LayoutParams sp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			dialog = new ProgressBar(context);
			//Resources res = getResources(); 
			//Drawable shape = res.getDrawable(R.drawable.my_progress_indeterminate);
			//dialog.setIndeterminateDrawable(shape);
			
			tv = new TextView(context);
			tv.setText("Loading...");
			tv.setPadding(30, 0, 0, 0);
			ll.addView(dialog, sp);
			ll.addView(tv);
			
        	flipper.addView(ll);
        	
        	Log.d("C2DM", "year:" + frm_year + "  month: " + frm_month + "  order: " + order + "  idx: ");
		}

		protected void onPreExecute(){
		}

		protected Void doInBackground(Void... unused){
			md_array = setData(context, frm_year, frm_month, memDuesList);
    		return null;
        }

        protected void onPostExecute(Void unused)
        {
       		//flipper.removeView(dialog);
        	dialog.setVisibility(View.GONE);
        	tv.setVisibility(View.GONE);
        	
        	
        	if(FIRST_CHECK < 9 && initDialog.isShowing())
        		initDialog.dismiss();
        	
            //LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        	//LinearLayout ll = new LinearLayout(context);
        	//sv.addView(ll);
        	
        	
        	ll.setGravity(Gravity.TOP);
            FrameLayout.LayoutParams sp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        	ScrollView sv = new ScrollView(context);
        	//sv.setFillViewport(true);
        	
            TableLayout table	= new TableLayout(context);
            
            FrameLayout.LayoutParams fParam = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
            table.setLayoutParams(fParam);
            
            TableRow trDate		= new TableRow(context);
            
            TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            TableRow.LayoutParams cellLp = new TableRow.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1.0f);
            
            
            TextView tdDate	= new TextView(context);
            tdDate.setText(frm_year + "년 " + frm_month + "월");
            tdDate.setGravity(Gravity.CENTER);
            tdDate.setTextColor(0xFFFFFFFF);
            tdDate.setBackgroundColor(0xFFD34937);
            tdDate.setPadding(20, 10, 20, 10);
            tdDate.setHeight(60);
            tdDate.setTextSize(20);
            
            cellLp.setMargins(0, 3, 0, 3);
            trDate.addView(tdDate, cellLp);
            table.addView(trDate, rowLp);
            
            
            TableRow trTop		= new TableRow(context);
            
            TextView tdTop		= new TextView(context);
            tdTop.setText("항목");
            tdTop.setGravity(Gravity.CENTER);
            tdTop.setTextColor(0xFFFFFFFF);
            tdTop.setBackgroundColor(0xFF787974);
            tdTop.setPadding(20, 10, 20, 10);
            tdDate.setTextSize(18);
            
            TextView td2Top	= new TextView(context);
            td2Top.setText("수입");
            td2Top.setGravity(Gravity.CENTER);
            td2Top.setTextColor(0xFFFFFFFF);
            td2Top.setBackgroundColor(0xFF787974);
            td2Top.setPadding(20, 10, 20, 10);
            
            TextView td3Top	= new TextView(context);
            td3Top.setText("지출");
            td3Top.setGravity(Gravity.CENTER);
            td3Top.setTextColor(0xFFFFFFFF);
            td3Top.setBackgroundColor(0xFF787974);
            td3Top.setPadding(20, 10, 20, 10);
            
            cellLp.setMargins(0, 0, 0, 1);
            trTop.addView(tdTop, cellLp);
            trTop.addView(td2Top, cellLp);
            trTop.addView(td3Top, cellLp);

            table.addView(trTop, rowLp);
            
            
            int bgColor		= 0xFFFFFFFF;
            int fontColor	= 0xFF515151;
            for(int i = 0 ; i < md_array.size(); i++){
            	
            	if(i % 2 == 0)
            		bgColor = 0xFFE7EBEE;
            	else
            		bgColor = 0xFFFFFFFF;
            	
            	if( i+1 == md_array.size()){
            		fontColor	= 0xFFFFFFFF;
            		bgColor		= 0xFF787974;
            	}else{
            		fontColor = 0xFF515151;
            	}
            	
    	        TableRow tr		= new TableRow(context);
    	        
    	        TextView td		= new TextView(context);
    	        td.setText(md_array.get(i).getAccTitle());
    	        td.setGravity(Gravity.LEFT);
    	        td.setTextColor(fontColor);
    	        td.setBackgroundColor(bgColor);
    	        td.setPadding(20, 10, 0, 10);
    	        td.setTextSize(18);
    	        td.setMaxWidth(150);
    	        //td.setHeight(60);
    	        
    	        TextView td2	= new TextView(context);
    	        td2.setText(md_array.get(i).getAccIn());
    	        td2.setGravity(Gravity.RIGHT);
    	        td2.setTextColor(fontColor);
    	        td2.setBackgroundColor(bgColor);
    	        td2.setPadding(10, 10, 20, 10);
    	        td2.setTextSize(18);
    	        //td.setHeight(60);
    	        
    	        TextView td3	= new TextView(context);
    	        td3.setText(md_array.get(i).getAccOut());
    	        td3.setGravity(Gravity.RIGHT);
    	        td3.setTextColor(fontColor);
    	        td3.setBackgroundColor(bgColor);
    	        td3.setPadding(10, 10, 20, 10);
    	        td3.setTextSize(18);
    	        //td.setHeight(60);
    	        
    	        tr.addView(td, cellLp);
    	        tr.addView(td2, cellLp);
    	        tr.addView(td3, cellLp);
    	        
    	        if(i == 0){
    	        	td.setTextColor(0xFF5E87B0);
    	        	td.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
	    	        td.setOnClickListener(new View.OnClickListener() {
	    	               @Override
	    	                public void onClick(View v) {	    	            	   
	    	            	   	new AlertDialog.Builder(context)
	    	            	   		.setIcon(R.drawable.icon_sja)		// icon 지정 후 Builder 객체 리턴
	    	            	   		.setTitle(frm_year + "년 " + frm_month + "월 회비")			// title 지정
	    	            	   		//.setMessage("메시지 영역")			// 메시지 text 지정
	    	            	   		.setView(createCustomView(memDuesList))	// 커스텀 뷰 지정
	    	            	   		// AlertDialog의 버튼 생성 & 버튼 클릭 이밴트에 대한 Listener 객체 생성/등록 
	    	            	   		.setPositiveButton("닫기", new DialogInterface.OnClickListener(){
	    	            	   			public void onClick(DialogInterface dialog, int which) {
	    	            	   				dialog.dismiss();
	    	            	   			}
	    	            	   		})
	    	            	   		.show(); // 지금까지 설정한 dialog를 화면에 보이고 AlertView객체를 return
	    	                }
	    	        });
    	        }
    	
    	        table.addView(tr, rowLp);
            }
            
            if(md_array.size() == 0){
	            TableRow trNodata		= new TableRow(context);
	            
	            TextView tdNodata		= new TextView(context);
	            tdNodata.setText("데이터가 없습니다.");
	            tdNodata.setGravity(Gravity.CENTER);
	            tdNodata.setPadding(0, 30, 0, 30);
	            trNodata.addView(tdNodata, cellLp);
	
	            table.addView(trNodata, rowLp);
            }
            
            NumberFormat currencyFormatter = NumberFormat.getInstance();
    	    TableRow trBottom		= new TableRow(context);
            
            TextView tdBottom		= new TextView(context);
            tdBottom.setText("현재 잔액: " + currencyFormatter.format(GROUP_BALANCE));
            tdBottom.setGravity(Gravity.RIGHT);
            tdBottom.setTextColor(0xFFD34937);
            tdBottom.setBackgroundColor(0xFFFFFFFF);
            tdBottom.setPadding(0, 10, 20, 10);
            tdBottom.setTextSize(18);
            
            
            trBottom.addView(tdBottom, cellLp);
            //trBottom.addView(td2Bottom, cellLp);
            //trBottom.addView(td3Bottom, cellLp);

            table.addView(trBottom, rowLp);
			
			//ll.addView(table);
			//sv.addView(ll,lParam);
			//sv,sp
			
			/*
	        String[] names = new String[] { "Cupcake", "Donut", "Eclair", "Froyo",
					"Gingerbread", "Honeycomb", "IceCream Sandwich", "Donut", "Eclair", "Froyo",
					"Gingerbread", "Honeycomb", "IceCream Sandwich", "Donut", "Eclair", "Froyo",
					"Gingerbread", "Honeycomb", "IceCream Sandwich", "Donut", "Eclair", "Froyo",
					"Gingerbread", "Honeycomb", "IceCream Sandwich"};
			
			//GridView gv = (GridView) findViewById(R.id.grid);
			
	        
	        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View test = mInflater.inflate(R.layout.account_girdview_test, null);
			GridView gv = (GridView) findViewById(R.id.grid);
			ArrayAdapter<String> aa = new ArrayAdapter<String>(	context ,android.R.layout.simple_list_item_1,names );
			gv.setAdapter(aa);
			*/
			
			sv.addView(table);
			sv.setOnTouchListener(this);
			ll.addView(sv,sp);
			
            
            
            if(FIRST_CHECK == 9){
            	initPrevMonthBackground();
            	FIRST_CHECK = 0;
            }
            
        }

        public void onCancel(DialogInterface dialog)
        {
        	cancel(true);
        	dialog.dismiss();
        }

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			//Log.d("C2DM", " GRID ------------------");
			onUp(v, event);
			return false;
		}
	}
	

	class memDues{
		String memName;
		int dueAmount;
		
		public memDues(String memName, int dueAmount){
			this.memName = memName;
			this.dueAmount = dueAmount;
		}
		
		public String getMemName(){
			return memName;
		}
		
		public int getDueAmount(){
			return dueAmount;
		}
	}
	
	private class PersonAdapter extends ArrayAdapter<memDues> {

        private ArrayList<memDues> items;

        public PersonAdapter(Context context, int textViewResourceId, ArrayList<memDues> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        	NumberFormat currencyFormatter = NumberFormat.getInstance();
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.account_member_due_popup, null);
            }
            
            memDues p = items.get(position);
            if (p != null) {
                    TextView tt = (TextView) v.findViewById(R.id.toptext);
                    TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                    if (tt != null){
                    	tt.setText(p.getMemName());
                    }
                    if(bt != null){
                    		bt.setText(currencyFormatter.format(p.getDueAmount()));
                    }
            }
            
            return v;
        }
	}
	
	private class getGroupBalance extends AsyncTask<Void, Void, Void>{
		private ProgressDialog dialog;
		private Context context;
		private JSONArray json_result;
		
		private getGroupBalance(Context context){
			this.context	= context;
		}

		protected void onPreExecute(){
			//dialog = ProgressDialog.show(context, "", "Loading. Please wait...", true);
		}

		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				JSONObject json = new JSONObject(hcm.readJSON(context.getString(R.string.SERVER_URL) + "info/service_group_info.php", null));
				JSONArray groupInfo = json.getJSONArray("data_result");
				JSONObject groupInfoJSONObject = groupInfo.getJSONObject(0);
				JSONSharedPreferences.saveJSONObject(context, "gline", "groupInfo", groupInfoJSONObject);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
    		return null;
        }

        protected void onPostExecute(Void unused)
        {
            //dialog.dismiss();
        	
        	JSONObject jsonObject = new JSONObject();
    		try {
    			jsonObject = JSONSharedPreferences.loadJSONObject(context, "gline", "groupInfo");
    			
    			GROUP_CREATED_DATE = jsonObject.getInt("GROUP_CREATED_DATE");
    			GROUP_BALANCE = jsonObject.getInt("GROUP_BALANCE");
    			
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		initThisMonthBackground();
            //TextView mainNoticeViewHeader = (TextView)findViewById(R.id.mainNoticeViewHeader);
            //mainNoticeViewHeader.setText("최신공지사항: [" + tmp_nd.getReg_date() + "]" + tmp_nd.getTitle());
            
            //TextView mainNoticeView = (TextView)findViewById(R.id.mainNoticeView);
            //mainNoticeView.setText(tmp_nd.getContent());
        }

	}
	
}
